package gm.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GMClientActivity extends Activity {
	
    // timeout in millisecondi (aspetta per la connessione)
    private static final int CONN_TIMEOUT = 3000;

    // timeout in millisecondi della socket (aspetta per i dati)
    private static final int SOCKET_TIMEOUT = 5000;
    
    
    private static final String NOTIFICA_URL = "http://10.0.2.2:8080/GestioneMulteServer/gestioneMulte/notifica";      
    private static final String VERBALE_URL = "http://10.0.2.2:8080/GestioneMulteServer/gestioneMulte/verbale";
    private static final String GMAP_URL = "http://maps.googleapis.com/maps/api/geocode/json?latlng=20.89,38.492222&sensor=true";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //HttpResponse response = inviaNotifica(NOTIFICA_URL);
        //HttpResponse response = inviaVerbale(VERBALE_URL);
       
        String result = "";
        try {
			//result = inputStreamToString(response.getEntity().getContent());
			result = giveMeStreet(GMAP_URL);

		} catch (Exception e) {
			e.printStackTrace();
		}
        TextView testo =  (TextView) findViewById(R.id.testo);
        testo.setText(result);
        
    }    
    
    private String giveMeStreet(String url) {	 

	     HttpClient httpclient = new DefaultHttpClient();
	     HttpResponse response = null;
	     String result="";
		 try{     	 
			    	
		   	 HttpGet httpGet = new HttpGet(url);
		   	 response = httpclient.execute(httpGet);		   	 
		   	 String jsonReceived = inputStreamToString(response.getEntity().getContent());
		   	 JSONObject json = new JSONObject(jsonReceived);
		   	 
		   	 JSONArray received = json.getJSONArray("results");
		   	 JSONObject internal_json =(JSONObject) received.get(0);
		   	 result = internal_json.getString("formatted_address");
		   	 
		   	 
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	   
	    return result;
	}

    

	
    private HttpResponse inviaNotifica(String url) {	 

	     HttpClient httpclient = new DefaultHttpClient(getHttpParams());
	     HttpResponse response = null;
	     
	     //definisco parametri notifica
         GregorianCalendar current_time = new GregorianCalendar();       
         String data_ora = getDateTimeCurrent(current_time);
         String via_comune = "Via Giuseppe Luzi 14 Frascati";
         double sanzione = 100.0;
         //String n_verbale = "N_verbale";
         String n_verbale = "";
         String targa = "DA478TY";
         
	     Notifica notifica = new Notifica(data_ora,via_comune,sanzione,n_verbale,targa);
	     ArrayList<Integer> infrazioni = new ArrayList<Integer>();
	     infrazioni.add(35);
	     infrazioni.add(53);
	     ArrayList<String> descInfrazioni = new ArrayList<String>();
	     descInfrazioni.add("sosta in ds");
	     descInfrazioni.add("eccesso velocità");
	     notifica.setInfrazioni(infrazioni);
	     
	     notifica.setDescrizioneInfrazione(descInfrazioni);
	     
		 try{     	 
		   	 JSONObject json = new JSONObject();
		   	 json.put("nverbale", notifica.getVerbaleNumber());
		   	 json.put("data_ora", notifica.getDataOra());
		   	 json.put("via_comune", notifica.getViaComune());
		   	 json.put("sanzione", notifica.getSanzione());
		   	 json.put("infrazioni", new JSONArray(notifica.getInfrazioni()));
		   	 json.put("descrizioneInfrazioni", new JSONArray(notifica.getDescrizioneInfrazione()));
		   	 json.put("targa", notifica.getTarga());
		   	 
		   	 StringEntity entity = new StringEntity( json.toString());  		    	
		   	 HttpPost httppost = new HttpPost(url);
		   
		     entity.setContentType("application/json;charset=UTF-8");
		     entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
		     httppost.setEntity(entity);
		   	 response = httpclient.execute(httppost);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	   
	    return response;
	}

    
    // stabilisce la connessione e i socket fissando i timeout
    private HttpParams getHttpParams() {
        HttpParams htpp = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
        return htpp;
    }
    
    
    public static String getDateTimeCurrent(GregorianCalendar current){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data =  format.format(current.getTime());
         return data;

    }
    
    public static String getDateCurrent(GregorianCalendar current){


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String data =  format.format(current.getTime());
         return data;


      }
    
    
    private String inputStreamToString(InputStream is) {

        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is),8000);

        try {
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Return full string
        return total.toString();
    }
 
    
    private HttpResponse inviaVerbale(String url) {	 

	     HttpClient httpclient = new DefaultHttpClient(getHttpParams());
	     HttpResponse response = null;
	     
         GregorianCalendar current_time = new GregorianCalendar();       
         String data_ora = getDateTimeCurrent(current_time);
         GregorianCalendar dnt =  new GregorianCalendar(1990, Calendar.DECEMBER, 12);
         String DataNascitaTrasgr = getDateCurrent(dnt);
         GregorianCalendar drd =  new GregorianCalendar(2008, Calendar.OCTOBER, 13);
         String documentoRilasciatoData = getDateCurrent(drd);
         GregorianCalendar dnp =  new GregorianCalendar(1971, Calendar.JANUARY, 1);
         String DataNascitaPoss = getDateCurrent(dnp);
	     
	     Verbale verbale = new Verbale( "2134",	data_ora,"Frascati",
				   						"sottoscritti", "nome_cognome_trasgressore",
				                        "NascitaTrasgressore", "ProvNascitaTrasgr",
									    DataNascitaTrasgr, "residenzaTrasgr",
									   "provResidenzaTrasgr", "documento",
									   "nDocTrasgr",  documentoRilasciatoData,
									   "documentoRilasciatoDa", "veicolo",
									   "targa",	"nome_cognome_possessore",
									   "NascitaPossessore",	 "ProvNascitaPoss",
									   DataNascitaPoss, "residenzaPoss",
									   "provResidenzaPoss",	 "violazioni",
									   "dichiara",	 "130.21");
	     
	     try{     	 
		   	 JSONObject jsonVerbale = new JSONObject();
			jsonVerbale.put("numeroVerbale", verbale.getNumeroVerbale());
			jsonVerbale.put("data_ora", verbale.getData_ora());
			jsonVerbale.put("luogoTrasgressione", verbale.getLuogoTrasgressione());
			jsonVerbale.put("sottoscritti", verbale.getSottoscritti());
			jsonVerbale.put("nome_cognome_trasgressore", verbale.getNome_cognome_trasgressore());
			jsonVerbale.put("NascitaTrasgressore", verbale.getNascitaTrasgressore());
			jsonVerbale.put("ProvNascitaTrasgr", verbale.getProvNascitaTrasgr());
			jsonVerbale.put("DataNascitaTrasgr", verbale.getDataNascitaTrasgr());
			jsonVerbale.put("residenzaTrasgr", verbale.getResidenzaTrasgr());
			jsonVerbale.put("provResidenzaTrasgr", verbale.getProvResidenzaTrasgr());
			jsonVerbale.put("documento", verbale.getDocumento());
			jsonVerbale.put("nDocTrasgr", verbale.getnDocTrasgr());
			jsonVerbale.put("documentoRilasciatoData", verbale.getDocumentoRilasciatoData());
			jsonVerbale.put("documentoRilasciatoDa", verbale.getDocumentoRilasciatoDa());
			jsonVerbale.put("veicolo", verbale.getVeicolo());
			jsonVerbale.put("targa", verbale.getTarga());
			jsonVerbale.put("nome_cognome_possessore", verbale.getNome_cognome_possessore());
			jsonVerbale.put("NascitaPossessore", verbale.getNascitaPossessore());
			jsonVerbale.put("ProvNascitaPoss", verbale.getProvNascitaPoss());
			jsonVerbale.put("DataNascitaPoss", verbale.getDataNascitaPoss());
			jsonVerbale.put("residenzaPoss", verbale.getResidenzaPoss());
			jsonVerbale.put("provResidenzaPoss", verbale.getProvResidenzaPoss());
			jsonVerbale.put("violazioni", verbale.getViolazioni());
			jsonVerbale.put("dichiara", verbale.getDichiara());
			jsonVerbale.put("sanzione", verbale.getSanzione());
		   	 
		   	 StringEntity entity = new StringEntity( jsonVerbale.toString());  		    	
		   	 HttpPost httppost = new HttpPost(url);
		   
		     entity.setContentType("application/json;charset=UTF-8");
		     entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
		     httppost.setEntity(entity);
		   	 response = httpclient.execute(httppost);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	   
	    return response;
	}

	    
    


}